<template>
  <div>
    <TopFilter ref="topFilterFormPanel" :list="topFilterList" :cols="4" :labelWidth="90" :collapse="false" :isSubmitBtn="false"></TopFilter>
    <FilterTable
      ref="inTable"
      columnsRef="partPartInventoryAdjustInventoryIndex"
      :columns="columns"
      :dataSource="tableData"
      :onSyncTableData="hadnleTableDataChange"
      :onRowSelectChange="handleTableRowSelectChange"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="moreActions">
        <span @click="deleteRow">删除明细</span>
      </template>
      <template slot="controls">
        <el-button size="small" type="primary" :disabled="beforeAddFlag" @click="beforeAdd">新建</el-button>
        <el-button size="small" type="primary" :disabled="addFlag" @click="addNewPartFun">添加配件</el-button>
        <AjaxButton size="small" type="primary" :disabled="saveFlag" :click="save">保存</AjaxButton>
        <AjaxButton size="small" type="primary" :disabled="inFlag" :click="inStock">入库</AjaxButton>
        <el-button size="small" type="primary" :disabled="cancelFlag" @click="cancel">取消</el-button>
        <el-button size="small" type="primary" :disabled="quitFlag" @click="quit">作废</el-button>
        <el-button size="small" type="primary" :loading="assignLeisureLoading" :disabled="addFlag" @click="handleAssignLeisurePosition">默认空库位</el-button>
        <el-button size="small" type="primary" icon="el-icon-printer" :disabled="printFlag" @click="print">打印</el-button>
      </template>
    </FilterTable>
    <div v-if="printBtn">
      <BasePrint :title="入库单" ref="Salesprint" :data="SalesprintList" template="templatepartInventory" />
      <!-- 原templatePartAdjustInventory -->
    </div>
    <Drawer :visible.sync="showAddNewPart" title="借进入库单新增" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <addNewPart @close="closeHandler" @addNewPart="setNewPartData" @addNewPartnew="addNewPartnew" />
    </Drawer>
    <BaseDialog :visible.sync="showEditPart" title="借进入库单编辑" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <editPartPage :editRowData="editRow" :billNo="BILL_NO" @close="closeHandler" @editPart="editPartData" />
    </BaseDialog>
    <BaseDialog :visible.sync="showSearchCustomer" title="供应商选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <searchCustomer :customerNo="this.topFilterList[1].initialValue" @close="closeHandler" @addCustomerCode="setCustomerInfo" />
    </BaseDialog>
    <BaseDialog :visible.sync="showSearchInorder" title="借进入库单选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <searchInOrder :ptype="ptype" :orderNo="this.topFilterList[0].initialValue" @close="closeHandler" @showOrder="showOrderDetail" />
    </BaseDialog>
    <!-- 库位选择弹窗 -->
    <BaseDialog title="选择库位" width="30%" :visible.sync="positionListVisible" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <positionSelect :positionList="positionDialogList" :editRow="positionEditRow" @onConfirm="handlePositionSelectConfirm" @close="positionListVisible = false" />
    </BaseDialog>
    <!-- 对应单号选择弹窗 -->
    <BaseDialog title="对应单选择" :visible.sync="visibleBillNo" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <billNo :rowData="inTableListData" :billNo="BILL_NO" @onConfirm="handleBillNoConfirm" @close="visibleBillNo = false" />
    </BaseDialog>
  </div>
</template>

<script>
import { saveOrder, showDetailRequest, deleteOrder, stockIn, printData } from '@/api/part/partInventory/adjustInventory/index';
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
import searchCustomer from './searchCustomerPage';
import addNewPart from './addNewPartPage';
import editPartPage from './editPartPage';
import searchInOrder from './searchAllocateInOrderPage';
import billNo from './billNo';
import * as Util from '@/utils/index.js';
import { getDealerUser, queryUseablePositionListByStorage, queryParyHasStorageById } from '@/api/part/partInventory/partInventory';
import { getStorageList, queryTex, queryBorrowPartCount } from '@/api/part/common';
import positionSelect from '@/pages/part/partInventory/partInventory/components/positionSelect';
import { dealerPrintApi } from '@/api/repair/index.js';

export default {
  name: 'partAdjustInventory',
  components: {
    searchInOrder,
    searchCustomer,
    addNewPart,
    editPartPage,
    positionSelect,
    billNo
  },
  mixins: [dictionary],
  data() {
    this.conf = { add: '新增', edit: '编辑', show: '显示' };
    this.inTableData = null;
    return {
      cunUserList: [], // 存所有人的数组
      printDataList: [], // 存打印接口返回的数据
      SalesprintList: {}, // 打印的数据
      printBtn: false, // 控制打印
      beforeAddFlag: false,
      addFlag: true,
      saveFlag: true,
      inFlag: true,
      cancelFlag: true,
      quitFlag: true,
      printFlag: true, // 原true
      topFilterList: this.createTopFilterList(),
      columns: this.createTableColumns(),
      fetchParams: {},
      visible: false,
      dialogTitle: '',
      partAllocateInID: '',
      showSearchCustomer: false,
      showSearchInorder: false,
      showAddNewPart: false,
      showEditPart: false,
      isFinished: false,
      inTableListData: [], // table列表数据
      tableData: [],
      editRow: {}, // 保存修改行数据
      deleteRows: '', // 删除行ITEM_ID
      selectedTableRowData: [], // 选中的table行项
      positionListVisible: false, // 是否显示库位选择弹窗
      storageDic: [], // 仓库字典
      storagePositionList: {
        // table仓库库位篮子
        // sotrageCode: [posCode1, posCode1]
      },
      positionEditRow: {}, // 正在选择库位的行项数据
      positionDialogList: [], // 弹窗选择库位的库位
      assignLeisureLoading: false, // 赋值空库位按钮loading状态
      tax: 0, // 税率
      visibleBillNo: false, // 对应单号弹窗是否显示
      BILL_NO: '',
      printParams: {} // 打印参数
    };
  },
  computed: {
    ptype() {
      return this.$route.meta.ptype;
    },
    billNo() {
      return this.topFilterList.find(item => item.fieldName == 'allocateType').initialValue;
    },
    allocateInNoCol() {
      return this.topFilterList.find(item => item.fieldName == 'allocateInNo').initialValue;
    }
  },
  watch: {
    billNo(newVal, oldVal) {
      let res = newVal == '82121001';
      this.topFilterList.find(item => item.fieldName == 'allocateOutNo').disabled = res;
      // 判断添加配件按钮可点击
      if (this.beforeAddFlag) {
        this.addFlag = !res;
      }
    }
    // beforeAddFlag(newVal, oldVal) {
    //   if (!newVal) {
    //     let temp = this.topFilterList.find(item => item.fieldName == 'allocateOutNo').disabled;
    //     // console.log(temp, 'slsllal');
    //     this.addFlag = !temp;
    //   }
    //   this.topFilterList.find(item => item.fieldName == 'allocateType').disabled = !newVal;
    // }
  },
  created() {},
  mounted() {
    this.inTableData = this.$refs.inTable;
    this.getDealerUser();
    this.queryPrintParams();
  },
  methods: {
    // 对应单号弹窗确定按钮
    handleBillNoConfirm(val) {
      this.topFilterList.find(item => item.fieldName == 'allocateOutNo').initialValue = val[0].ALLOCATE_OUT_NO;
      this.topFilterList.find(item => item.fieldName == 'customerCode').initialValue = val[0].CUSTOMER_CODE;
      this.topFilterList.find(item => item.fieldName == 'customerName').initialValue = val[0].CUSTOMER_NAME;
      this.$refs.inTable.EXECUTE_INSERT(val);
      this.topFilterList.find(item => item.fieldName == 'allocateOutNo').disabled = true;
      this.topFilterList.find(item => item.fieldName == 'allocateType').disabled = true;
      // this.visibleBillNo = false;
    },
    // 对应单号选择点击
    billNoHandle() {
      this.BILL_NO = this.topFilterList.find(item => item.fieldName == 'allocateOutNo').initialValue;
      this.visibleBillNo = true;
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '借进入库单号',
          fieldName: 'allocateInNo',
          placeholder: '请选择...',
          unitRender: props => {
            return <el-button icon="el-icon-search" onClick={() => this.searchInOrderFun()}></el-button>;
          }
        },
        {
          type: 'INPUT',
          label: '供应商代码',
          fieldName: 'customerCode',
          placeholder: '请选择...',
          readonly: true,
          disabled: true,
          rules: [{ required: true, message: '这是必填字段', trigger: 'blur' }],
          unitRender: props => {
            return <el-button icon="el-icon-search" onClick={() => this.searchCustomerFun()}></el-button>;
          }
        },
        {
          type: 'DATE',
          label: '入库日期',
          disabled: true,
          fieldName: 'stockInDate',
          valueFormat: 'YYYY-MM-DD HH:mm:ss'
        },
        {
          type: 'INPUT',
          label: '供应商名称',
          fieldName: 'customerName',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '默认仓库',
          fieldName: 'defaultStorage',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '默认库区',
          fieldName: 'areaCode',
          disabled: false,
          change: val => {
            this.handleAreaCodeChange(val);
            console.log(val, '库区变化');
          }
        },
        {
          type: 'RADIO',
          label: '类型区分',
          fieldName: 'allocateType',
          initialValue: '82121001',
          disabled: true,
          itemList: [
            { text: '借进入库', value: '82121001' },
            { text: '还入入库', value: '82121002' }
          ],
          placeholder: ''
          // rules: [{ required: true, message: '请选择出库日期', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '借出单号',
          fieldName: 'allocateOutNo',
          placeholder: '请选择...',
          disabled: true,
          unitRender: props => {
            return <el-button icon="el-icon-search" onClick={() => this.billNoHandle()}></el-button>;
          }
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'code',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: props => {
            return (
              <div>
                <el-button disabled={this.isFinished} size="mini" type="text" onClick={() => this.editHandle(props.row)}>
                  编辑
                </el-button>
              </div>
            );
          }
        },
        // <el-button disabled={this.isFinished} size="mini" type="text" onClick={() => this.deleteRow(props.row)}>
        //   删除
        // </el-button>
        {
          title: '仓库',
          dataIndex: 'STORAGE_CODE',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: params => {
            let storage = params.row.STORAGE_CODE;
            let positionCode = params.row.STORAGE_POSITION_CODE;
            return (
              <el-select
                value={params.row.STORAGE_CODE}
                disabled={(!!params.row.ITEM_ID && params.row.ITEM_ID != 'N') || !Util.isAuthorized('1313', '13131013')}
                placeholder="请选择..."
                onChange={val => {
                  // 当仓库改变时将现有库位增加到该仓库库位篮子中
                  if (this.storagePositionList[storage] && positionCode && !this.storagePositionList[storage].includes(positionCode)) {
                    this.storagePositionList[storage].unshift(positionCode);
                  }
                  params.row.STORAGE_CODE = val;
                  params.row.STORAGE_POSITION_CODE = '';
                }}
              >
                {this.storageDic.map((item, index) => (
                  <el-option key={index} label={item.text} value={item.value}></el-option>
                ))}
              </el-select>
            );
          }
        },
        {
          title: '库位',
          width: 170,
          dataIndex: 'STORAGE_POSITION_CODE',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: params => {
            return (
              <el-input disabled={!!params.row.ITEM_ID && params.row.ITEM_ID != 'N'} placeholder="请选择..." value={params.row.STORAGE_POSITION_CODE} readonly size="mini">
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  onClick={() => {
                    this.handleChosePosition(params.row);
                  }}
                ></el-button>
              </el-input>
            );
          }
        },
        { title: 'ITEM_ID', dataIndex: 'ITEM_ID', sorter: true, filter: true, hidden: true, filterType: 'input' },
        { title: 'FLAG', dataIndex: 'FLAG', sorter: true, filter: true, hidden: true, filterType: 'input' },
        { title: '配件代码', dataIndex: 'PART_NO', sorter: true, filter: true, filterType: 'input' },
        { title: '配件名称', dataIndex: 'PART_NAME', sorter: true, filter: true, filterType: 'input' },
        { title: '计量单位', dataIndex: 'UNIT_NAME', sorter: true, filter: true, filterType: 'input' },
        { title: '入库数量', dataIndex: 'IN_QUANTITY', sorter: true, filter: true, filterType: 'input', precision: 2 },
        { title: '入库不含税单价', dataIndex: 'IN_PRICE', sorter: true, filter: true, filterType: 'input', precision: 2 },
        { title: '入库不含税金额', dataIndex: 'IN_AMOUNT', sorter: true, filter: true, filterType: 'input', precision: 2 },
        {
          title: '类型区分',
          dataIndex: 'ALLOCATE_TYPE',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [
            { text: '借进入库', value: '82121001' },
            { text: '还入入库', value: '82121002' }
          ],
          dictItems: [
            { text: '借进入库', value: '82121001' },
            { text: '还入入库', value: '82121002' }
          ]
        }
      ];
    },
    hadnleTableDataChange(e) {
      // console.log(e, 1111111111111111111);
      this.inTableListData = e;
    },
    beforeAdd() {
      this.beforeAddFlag = true;
      this.topFilterList.find(item => item.fieldName == 'allocateType').disabled = false;
      this.saveFlag = false;
      this.cancelFlag = false;
      this.addFlag = false;
      this.printFlag = true;
      this.isFinished = false;
      // this.tableData = [];
      this.deleteRows = '';
      this.partAllocateInID = '';
      this.topFilterList.find(x => x.fieldName === 'allocateInNo').disabled = true;
      this.topFilterList.find(x => x.fieldName === 'customerCode').disabled = false;
      this.topFilterList.find(x => x.fieldName === 'allocateInNo').initialValue = '';
      this.topFilterList.find(x => x.fieldName === 'customerCode').initialValue = '';
      this.topFilterList.find(x => x.fieldName === 'stockInDate').initialValue = moment().format('YYYY-MM-DD HH:mm:ss');
      this.topFilterList.find(x => x.fieldName === 'customerName').initialValue = '';
      this.topFilterList.find(x => x.fieldName === 'remark').initialValue = '';
      this.topFilterList = [...this.topFilterList];
      this.quertStorageList();
    },
    // 打印数据接口
    async printData() {
      const res = await printData(this.partAllocateInID);
      if (!this.tax) {
        this.tax = (await queryTex()).data || 0.13;
      }
      res.data.detailInfo.map(item => {
        item.IN_AMOUNT_TAXED = item.IN_AMOUNT * (1 + this.tax * 1) || 0;
        item.IN_PRICE_TAXED = item.IN_PRICE * (1 + this.tax * 1) || 0;
      });
      this.printDataList = res.data;
    },
    // table选择选中变化
    handleTableRowSelectChange(e) {
      this.selectedTableRowData = e;
    },
    deleteRow(row) {
      Util.confirmAction('即将删除选中行项，是否继续')
        .then(confirm => {
          let itemIdArr = [];
          this.selectedTableRowData.map(item => {
            if (item.ITEM_ID) {
              itemIdArr.push(item.ITEM_ID);
            }
          });
          this.deleteRows = this.deleteRows + itemIdArr.length ? ',' + itemIdArr.join(',') : '';
          this.deleteRows = this.deleteRows.replace(/^\,/, '');
          this.$refs.inTable.EXECUTE_DELETE(this.selectedTableRowData);
          this.saveFlag = false;
          this.inFlag = true;
          this.quitFlag = true;
          this.$nextTick(() => {
            // 处理删除后序号不变问题
            this.inTableListData.map((item, index) => {
              item.index = index;
            });
          });
        })
        .catch(err => {});
    },
    async save() {
      this.$refs.topFilterFormPanel.SUBMIT_FORM();
      if (this.tableData.length == 0) {
        this.$notify({ title: '警告信息', message: '配件数据不能为空！', type: 'warning' });
        return;
      }
      // 增加表单校验空库位 AE-15987
      try {
        this.tableData.forEach(element => {
          if (!element['STORAGE_POSITION_CODE']) {
            this.$notify({ title: '警告信息', message: '库位代码不能为空！', type: 'warning' });
            throw 'error';
          }
        });
      } catch (error) {
        return;
      }
      if (
        this.topFilterList.find(x => x.fieldName === 'customerCode').initialValue == '' ||
        this.topFilterList.find(x => x.fieldName === 'customerCode').initialValue == null ||
        this.topFilterList.find(x => x.fieldName === 'customerName').initialValue == '' ||
        this.topFilterList.find(x => x.fieldName === 'customerName').initialValue == null
      ) {
        this.$notify({ title: '警告信息', message: '供应商代码和名称不能为空！', type: 'warning' });
      } else {
        let tableList = this.inTableListData;
        this.addFlag = false;
        this.inFlag = false;
        this.cancelFlag = false;
        this.quitFlag = false;
        this.saveFlag = true;
        let params = await this.$refs.topFilterFormPanel.GET_FORM_DATA();

        let allocateInCount = '';
        try {
          allocateInCount = (await queryBorrowPartCount()).data;
        } catch (err) {
          console.log(err);
        }

        let res = await saveOrder({
          ...this.fetchParams,
          ...params[1],
          items: this.deleteRows,
          remark: this.topFilterList.find(x => x.fieldName === 'remark').initialValue,
          customerCode: this.topFilterList.find(x => x.fieldName === 'customerCode').initialValue,
          customerName: this.topFilterList.find(x => x.fieldName === 'customerName').initialValue,
          dms_part_allocate_in: tableList.map(item => {
            const item2 = Object.assign({}, item);
            const returnObj = Util.camelCaseObject(item2);
            // console.log(item2, returnObj, this.inTableListData);
            return returnObj;
          }),
          allocateInCount,
          ptype: this.ptype ? this.ptype : null, // 模块区分
          allocateType: this.topFilterList.find(x => x.fieldName === 'allocateType').initialValue
        });

        if (res.resultCode === 200) {
          this.$notify.success({ title: '提示信息', message: '保存成功!' });
          let dataInfo = res.data.split(';');
          this.topFilterList.find(x => x.fieldName === 'allocateInNo').disabled = true;
          this.topFilterList.find(x => x.fieldName === 'allocateInNo').initialValue = dataInfo[0];
          this.deleteRows = '';
          this.tableData = [];
          this.showOrderItemDetail(dataInfo[1]);
        } else {
          this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
        }
      }
    },
    async inStock() {
      if (this.inTableListData == null || this.inTableListData.length == 0) {
        this.$notify({ title: '警告信息', message: '清单不能为空!', type: 'warning' });
        return;
      }
      let info = await stockIn({
        allocateInNo: this.topFilterList[0].initialValue,
        allocateInID: this.partAllocateInID
      });
      if (info.resultCode != 200) {
        return;
      }
      this.$notify.success({ title: '提示信息', message: '单据入账成功!' });
      this.tableData = [];
      this.showOrderItemDetail(this.partAllocateInID);
      this.topFilterList.find(x => x.fieldName === 'customerCode').disabled = true;
      this.topFilterList.find(x => x.fieldName === 'remark').disabled = true;
      this.isFinished = true;
      this.beforeAddFlag = true;
      this.inFlag = true;
      this.printFlag = false;
      this.addFlag = true;
      this.quitFlag = true;
      this.cancelFlag = false;
      this.printData();
    },
    async cancel() {
      this.beforeAddFlag = false;
      this.topFilterList.find(item => item.fieldName == 'allocateType').disabled = true;
      this.addFlag = true;
      this.saveFlag = true;
      this.inFlag = true;
      this.cancelFlag = true;
      this.quitFlag = true;
      this.printFlag = true;
      this.$refs.topFilterFormPanel.RESET_FORM();
      this.topFilterList.find(x => x.fieldName === 'allocateInNo').disabled = false;
      this.topFilterList.find(x => x.fieldName === 'customerCode').disabled = true;
      this.topFilterList.find(x => x.fieldName === 'remark').disabled = false;
      // this.topFilterList.find(x => x.fieldName === 'allocateInNo').initialValue = '';
      // this.topFilterList.find(x => x.fieldName === 'customerCode').initialValue = '';
      // this.topFilterList.find(x => x.fieldName === 'stockInDate').initialValue = '';
      // this.topFilterList.find(x => x.fieldName === 'customerName').initialValue = '';
      // this.topFilterList.find(x => x.fieldName === 'remark').initialValue = '';
      this.tableData = [];
      this.deleteRows = '';
      this.partAllocateInID = '';
      this.isFinished = false;

      this.$nextTick(() => {
        this.$refs.topFilterFormPanel.$refs.form.clearValidate();
      });
    },
    async quit() {
      let info = await deleteOrder(this.partAllocateInID);
      if (info.resultCode != 200) {
        return;
      }
      this.$notify.success({ title: '提示信息', message: '单据作废成功!' });
      this.cancel();
    },
    // 获取所有人的信息
    async getDealerUser() {
      const res = await getDealerUser();
      this.cunUserList = res.data;
    },
    // 执行打印的方法
    print() {
      this.printBtn = true;
      this.printData();
      // console.log(this.printDataList, '打印数据');
      this.SalesprintList = this.printDataList;
      let inType = this.topFilterList.find(item => item.fieldName == 'allocateType').initialValue;
      this.SalesprintList.baseInfo.STOCK_IN_TYPE = inType == 82121002 ? '还入入库' : '借进入库';
      this.cunUserList.forEach(x => {
        if (this.SalesprintList.baseInfo.USER_ID == x.userId) {
          this.SalesprintList.baseInfo.USER_NAME = x.employeeName;
        }
      });
      // 打印
      this.$nextTick(() => {
        this.$refs.Salesprint.EXCUTE_PRINT();
      });
    },
    // 往table中插入数据
    setNewPartData(val) {
      console.log(val, '往table中添加数据——旧');
      for (let i = 0; i < this.inTableListData.length; i++) {
        if (this.inTableListData[i].PART_NO == val.PART_NO && this.inTableListData[i].STORAGE_CODE == val.STORAGE_CODE && this.inTableListData[i].STORAGE_POSITION_CODE == val.STORAGE_POSITION_CODE) {
          this.$notify({ title: '警告信息', message: '相同配件不可以重复添加！', type: 'warning' });
          return;
        }
      }
      // 先赋值默认仓库
      let defaultStorageCode = this.topFilterList.find(item => item.fieldName == 'defaultStorage').initialValue;
      if (val.STORAGE_CODE == undefined || val.STORAGE_CODE == null || val.STORAGE_CODE == '') {
        val.STORAGE_CODE = defaultStorageCode || '';
      }
      this.topFilterList.find(item => item.fieldName == 'allocateType').disabled = true;
      this.$refs.inTable.EXECUTE_INSERT([val]);
      Util.notifyAction('添加成功', 'success');
    },
    addNewPartnew(val) {
      console.log(val, '往table中添加数据——新');
      for (let i = 0; i < this.inTableListData.length; i++) {
        if (this.inTableListData[i].PART_NO == val.PART_NO && this.inTableListData[i].STORAGE_CODE == val.STORAGE_CODE && this.inTableListData[i].STORAGE_POSITION_CODE == val.STORAGE_POSITION_CODE) {
          this.$notify({ title: '警告信息', message: '相同配件不可以重复添加！', type: 'warning' });
          return;
        }
      }
      this.inTableData.EXECUTE_INSERT(val);
      this.showAddNewPart = false;
    },
    editPartData(editVal) {
      this.showEditPart = false;
      for (var i = 0; i < this.inTableListData.length; i++) {
        if (this.inTableListData[i].index == editVal.editIndex) {
          this.inTableListData[i].IN_QUANTITY = editVal.IN_QUANTITY;
          this.inTableListData[i].IN_PRICE = editVal.IN_PRICE;
          this.inTableListData[i].IN_AMOUNT = editVal.IN_AMOUNT;
          this.inTableListData[i].FLAG = editVal.FLAG;
          this.inTableListData[i].STORAGE_POSITION_CODE = editVal.STORAGE_POSITION_CODE;
          this.inTableListData[i].PART_NAME = editVal.PART_NAME;
          this.inFlag = true;
          this.quitFlag = true;
          this.saveFlag = false;
          return;
        }
      }
    },
    setCustomerInfo(val) {
      this.topFilterList.find(x => x.fieldName === 'customerCode').initialValue = val[0].CUSTOMER_CODE;
      this.topFilterList.find(x => x.fieldName === 'customerName').initialValue = val[0].CUSTOMER_NAME;
    },
    showOrderDetail(val) {
      this.beforeAddFlag = true;
      this.saveFlag = false;
      this.cancelFlag = false;
      this.addFlag = false;
      this.printFlag = true;
      this.topFilterList.find(x => x.fieldName === 'allocateInNo').disabled = true;
      this.topFilterList.find(x => x.fieldName === 'customerCode').disabled = true;
      this.topFilterList.find(x => x.fieldName === 'stockInDate').disabled = true;
      this.topFilterList.find(x => x.fieldName === 'customerName').disabled = true;
      this.topFilterList.find(x => x.fieldName === 'allocateOutNo').disabled = true;
      this.topFilterList.find(x => x.fieldName === 'allocateType').disabled = true;
      this.topFilterList.find(x => x.fieldName === 'allocateInNo').initialValue = val[0].ALLOCATE_IN_NO;
      this.topFilterList.find(x => x.fieldName === 'allocateOutNo').initialValue = val[0].ALLOCATE_OUT_NO;
      this.topFilterList.find(x => x.fieldName === 'allocateType').initialValue = val[0].ALLOCATE_TYPE;
      this.topFilterList.find(x => x.fieldName === 'customerCode').initialValue = val[0].CUSTOMER_CODE;
      this.topFilterList.find(x => x.fieldName === 'stockInDate').initialValue = val[0].STOCK_IN_DATE;
      this.topFilterList.find(x => x.fieldName === 'customerName').initialValue = val[0].CUSTOMER_NAME;
      this.topFilterList.find(x => x.fieldName === 'remark').initialValue = val[0].REMARK;
      this.tableData = [];
      this.showOrderItemDetail(val[0].PART_ALLOCATE_IN_ID);
    },
    async showOrderItemDetail(partAllocateInId) {
      this.partAllocateInID = partAllocateInId;
      let infodata = await showDetailRequest(partAllocateInId);
      if (infodata.resultCode === 200) {
        this.inTableData.EXECUTE_INSERT(infodata.data);
        this.inTableData.EXECUTE_RESET_HEIGHT();
      } else {
        this.$notify.error({ title: '提示信息', message: res.errMsg || '单据查询失败!' });
      }
    },
    editHandle(row) {
      this.editRow = row;
      this.BILL_NO = this.BILL_NO = this.topFilterList.find(item => item.fieldName == 'allocateOutNo').initialValue;
      this.showEditPart = true;
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    closeHandler(val, type) {
      this.showAddNewPart = val;
      this.showSearchCustomer = val;
      this.showSearchInorder = val;
      this.showEditPart = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    addNewPartFun() {
      this.inFlag = true;
      this.quitFlag = true;
      this.saveFlag = false;
      this.showAddNewPart = true;
    },
    searchInOrderFun() {
      this.showSearchInorder = true;
    },
    searchCustomerFun() {
      this.showSearchCustomer = true;
    },
    // 字符串的下划线格式转驼峰格式，eg：hello_world => helloWorld
    underline2Hump(str) {
      var str1 = str.toLowerCase();
      while (str1.indexOf('_') != -1) {
        str1 = str1.replace(/_\w/, str1.substr(str1.indexOf('_') + 1, 1).toUpperCase());
      }
      return str1;
    },
    // JSON对象的key值转换为驼峰式
    jsonToHump(obj) {
      if (obj instanceof Array) {
        obj.forEach((v, i) => {
          this.jsonToHump(v);
        });
      } else if (obj instanceof Object) {
        Object.keys(obj).forEach(key => {
          var newKey = this.underline2Hump(key);
          if (newKey !== key) {
            obj[newKey] = obj[key];
            delete obj[key];
          }
          this.jsonToHump(obj[newKey]);
        });
      }
    },
    // 点击行项选择库位
    async handleChosePosition(row) {
      console.log(this.inTableListData);
      console.log(this.tableData);
      let rowStorageCode = row.STORAGE_CODE;
      // 判断该配件在该仓库中是否存在可用库位
      let checkResult = await queryParyHasStorageById({
        storageCode: rowStorageCode,
        partNo: row.PART_NO
      });
      if (checkResult.data.length && checkResult.data[0].storagePositionCode) {
        Util.notifyAction('该配件在此仓库中存在可用库位不能修改库位', 'warning');
        let positionCode = checkResult.data[0].storagePositionCode;
        // 如果库位篮子中有此库位将此库位移除并且赋值给行项
        this.storagePositionList[rowStorageCode] &&
          this.storagePositionList[rowStorageCode].includes(positionCode) &&
          this.storagePositionList[rowStorageCode].splice(this.storagePositionList[rowStorageCode].indexOf(positionCode), 1);
        this.inTableListData[row.index].STORAGE_POSITION_CODE = positionCode;
        return;
      }
      // 判断该配件是否存在已选择库位的相同配件
      let listSamePartInfo = this.inTableListData.find(item => item.PART_NO == row.PART_NO && (item.STORAGE_POSITION_CODE || item.STORAGE_POSITION_CODE == 0)); // 配件号相同并且有库位的配件
      if ((listSamePartInfo && listSamePartInfo.STORAGE_POSITION_CODE) || listSamePartInfo.STORAGE_POSITION_CODE === 0) {
        Util.notifyAction('列表中存在相同配件，已自动赋值库位', 'warning');
        this.inTableListData[row.index].STORAGE_POSITION_CODE = listSamePartInfo.STORAGE_POSITION_CODE;
        return;
      }

      // console.log(row);
      // 修改库位时判断库位篮子里是否有该仓库的库位没有则查询并添加
      let rowSortagePosition = this.storagePositionList[rowStorageCode];
      if (!rowSortagePosition) {
        let res = await queryUseablePositionListByStorage({
          storageCode: rowStorageCode,
          areaCode: this.topFilterList.find(item => item.fieldName == 'areaCode').initialValue || ''
        });
        if (res.resultCode == 200) {
          if (res.data[0].error) {
            Util.notifyAction(res.data[0].error, 'warning');
          } else {
            this.storagePositionList[rowStorageCode] = res.data.map(item => item.storagePositionCode);
            this.handleChosePosition(row);
          }
        }
      } else {
        rowSortagePosition.includes(row.STORAGE_POSITION_CODE) && rowSortagePosition.splice(rowSortagePosition.indexOf(row.STORAGE_POSITION_CODE), 1);
        this.positionDialogList = rowSortagePosition;
        this.positionEditRow = row;
        this.positionListVisible = true;
      }
    },
    // 查询仓库字典(暂不控制oem非oem)
    async quertStorageList() {
      const ckRes = await getStorageList();
      const ckDict = ckRes.data.map(x => ({ text: x['STORAGE_NAME'], value: x['STORAGE_CODE'] }));
      this.columns.find(x => x.dataIndex === 'STORAGE_CODE').editItems = ckDict;
      this.columns.find(x => x.dataIndex === 'STORAGE_CODE').filterItems = ckDict;
      this.topFilterList.find(item => item.fieldName == 'defaultStorage').itemList = ckDict;
      this.topFilterList.find(item => item.fieldName == 'defaultStorage').initialValue = ckDict.length ? ckDict[0].value : '';
      this.storageDic = ckDict;
    },
    // 选择库位点击确定
    handlePositionSelectConfirm(e) {
      console.log(e, this.inTableListData, this.tableData);
      // 库位篮子中存在此库位将其移除
      try {
        this.storagePositionList[e.srotage] &&
          this.storagePositionList[e.srotage].includes(e.code) &&
          this.storagePositionList[e.srotage].splice(this.storagePositionList[e.srotage].indexOf(e.code), 1);
      } catch (err) {
        console.log(err);
      }
      e.oldCode && this.storagePositionList[e.srotage].unshift(e.oldCode); // 如果有旧库位则将旧库位插入到现有库位的最前方

      this.inTableListData[e.index].STORAGE_POSITION_CODE = e.code;
    },
    // 点击默认空库位(递归赋值操作)
    handleAssignLeisurePosition() {
      if (!this.inTableListData.length) {
        Util.notifyAction('请先添加配件明细', 'warning');
        return;
      }
      if (this.assignLeisureLoading) return;
      this.assignLeisureLoading = true;
      this.recursionAssignLeisurePosition(0);
    },
    // 递归赋值空闲库位
    async recursionAssignLeisurePosition(index) {
      if (index > this.inTableListData.length - 1) {
        this.assignLeisureLoading = false;
        Util.notifyAction('空闲库位赋值成功,若没有库位则此仓库或库区下没有可用库位', 'success');
      } else {
        let rowData = this.inTableListData[index];
        if (rowData.STORAGE_CODE && rowData.STORAGE_POSITION_CODE !== 0 && !rowData.STORAGE_POSITION_CODE) {
          let listSamePartInfo = this.inTableListData.find(item => item.PART_NO == rowData.PART_NO && (item.STORAGE_POSITION_CODE || item.STORAGE_POSITION_CODE == 0)); // 配件号相同并且有库位的配件
          if (listSamePartInfo && (listSamePartInfo.STORAGE_POSITION_CODE || listSamePartInfo.STORAGE_POSITION_CODE === 0)) {
            // 列表中已经有该配件并且已经赋值库位的情况下直接取已有库位
            this.inTableListData[index].STORAGE_POSITION_CODE = listSamePartInfo.STORAGE_POSITION_CODE;
            this.recursionAssignLeisurePosition(index + 1);
          } else if (this.storagePositionList[rowData.STORAGE_CODE] && this.storagePositionList[rowData.STORAGE_CODE].length) {
            // 当库位篮子中有此仓库的值并且此仓库可用库位列表不为空的时候取第一个空库位 赋值给当前行
            if (this.storagePositionList[rowData.STORAGE_CODE][0] || this.storagePositionList[rowData.STORAGE_CODE][0] === 0) {
              this.inTableListData[index].STORAGE_POSITION_CODE = this.storagePositionList[rowData.STORAGE_CODE][0];
              this.storagePositionList[rowData.STORAGE_CODE].splice(0, 1);
            }
            this.recursionAssignLeisurePosition(index + 1);
          } else {
            // 库位篮子中没有此库位的时候请求库位数据并添加到篮子中
            let res = await queryUseablePositionListByStorage({
              storageCode: rowData.STORAGE_CODE,
              areaCode: this.topFilterList.find(item => item.fieldName == 'areaCode').initialValue || ''
            });
            if (res.resultCode == 200 && !res.data[0].error) {
              this.storagePositionList[rowData.STORAGE_CODE] = res.data.map(item => item.storagePositionCode);
              this.recursionAssignLeisurePosition(index);
            } else {
              this.recursionAssignLeisurePosition(index + 1);
            }
          }
        } else {
          this.recursionAssignLeisurePosition(index + 1);
        }
      }
    },
    // 默认库区变化修改仓库篮子中的库位数据
    async handleAreaCodeChange(val) {
      let storageCode = this.topFilterList.find(item => item.fieldName == 'defaultStorage').initialValue;
      if (storageCode) {
        let res = await queryUseablePositionListByStorage({
          storageCode,
          areaCode: val
        });
        if (res.resultCode == 200) {
          if (!res.data.length) {
            notifyAction('新库区中无可用库位，可能导致无法选择库位，请重新输入', 'warning');
          }
          this.storagePositionList[storageCode] = res.data.map(item => item.storagePositionCode);
        }
      }
    },
    // 查询打印参数
    async queryPrintParams() {
      let res = await dealerPrintApi({
        vModule: '90211009',
        vNormalCode: 'BJJR'
      });
      if (res.resultCode == 200 && res.data.length) {
        this.printParams = res.data[0];
      }
      console.log(this.printParams, '打印参数');
    }
  }
};
</script>

<style lang="less" scoped></style>
